package com.data.hijack.analysis.template;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

import com.data.hijack.constant.Constants;
import com.data.hijack.util.Asserts;
import com.data.hijack.util.FileUtils;
import com.typesafe.config.ConfigException;

import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import my.common.convert.Converter;
import my.common.convert.ConverterFactory;
import my.common.convert.config.ConfigHolder;
import my.common.convert.config.TemplateConfigParser;
import my.common.convert.exception.MsgConvertException;

/**
 * @author husq
 */
public final class DataParser {
    private static ConverterFactory factory;
    private static Converter converter;

    public static Object parse(String msg, Map<String, String> sysConfig, String bizName, String msgType)
        throws MsgConvertException, IOException, my.common.convert.exception.ConfigException {
        factory = ConverterFactory.getInstance();
        converter = factory.getConverter();
        ConfigHolder holder = getConfigHolder(sysConfig, bizName);

        Object result = "";
        if (Constants.MSG_TYPE_JSON_DEF.equals(msgType)) {
            JSONObject jsonObj = JSONUtil.parseObj(msg);
            result = converter.convert(holder, jsonObj);
        } else {
            result = converter.convert(holder, msg);
        }

        return result;
    }

    private static ConfigHolder getConfigHolder(Map<String, String> sysConfig, String bizName)
        throws ConfigException, my.common.convert.exception.ConfigException, IOException {
        String key = bizName + Constants.DOT + Constants.TEMPLATE;
        String code = sysConfig.get(key);

        TemplateConfigParser parser = TemplateConfigParser.getInstance();
        String file =
            FileUtils.getFilePath(Constants.ANALYSIS_TEMPLATE, "xml", DataParser.class, Constants.TEMPLATE_CLASSPATH);
        Asserts.notNull(file, "Obtaining template configuration file");
        ConfigHolder holder = parser.parse(file, code);
        Map<String, Object> userObj = new HashMap<>();
        userObj.put(Constants.BIZ_CONFIG, sysConfig);
        holder.setUserObj("userObj", userObj);

        return holder;
    }
}
